package com.sinopec.uhf.chengwei

import android.util.Log
import com.rscja.deviceapi.RFIDWithUHFA8
import com.rscja.deviceapi.entity.UHFTAGInfo
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.isActive


internal object CoroutineRead {

    fun readATag(
        reader: RFIDWithUHFA8,
        config: Config = Config(),

        ): Flow<UHFTAGInfo?> {
        return channelFlow<UHFTAGInfo?> {
            //设置读取EPC数据
            //reader.setEPCMode()
            //设置读取EPC、TID数据
            //reader.setEPCAndTIDMode()
            //设置读取EPC、TID和USER数据
            reader.setEPCAndTIDUserMode(0,3)
            val isStartOk = reader.startInventoryTag()
            if (!isStartOk) {
                reader.stopInventory()
                throw CancellationException("开启识别标签失败")
            }
            delay(10)
            val consumer: ((UHFTAGInfo) -> Unit) = {
                Log.d("成为主机模式1：", "readATag: \nepc=${it.epc}\nuser=${it.user}\ntid=${it.tid}rssi=${it.rssi}")
                trySend(it)
                //把epc区写成0
                //val result: Boolean = reader.writeDataToEpc("00000000","861111111111")
                //val result: Boolean = reader.writeData("00000000",1,2,4,"861111111111")
                //Log.d("成为主机模式1把epc区写成0：", result.toString())
            }
            while (currentCoroutineContext().isActive) {
//                reader.stopInventory()
//                reader.startInventoryTag()
//                delay(100)
                readTagOneTime(reader, consumer)
                delay(config.readTagOneTime)
            }

            awaitClose {
                reader.stopInventory()
            }

        }
    }


    //读一次tag
    private fun readTagOneTime(
        reader: RFIDWithUHFA8,
        consumer: (UHFTAGInfo) -> Unit
    ) {
        val tag=reader.readTagFromBuffer()

        if (tag != null) {
            consumer(tag)
            readTagOneTime(reader, consumer)
        }
    }


}